# -*- coding:utf-8 -*-
from tornado import gen
import os

from appcommon.framework import WebBaseHandler
from common import utiltool
from common import timetool
import models as newsm
import settings


class UploadNewsImgHandler(WebBaseHandler):
    """
    上传图片
    """
    @gen.coroutine
    def post(self):
        file_metas = self.request.files['file']  # 提取表单中‘name’为‘file’的文件元数据
        current_time = timetool.get_timestamp()
        data = []
        for meta in file_metas:
            upload_path = settings.IMG_BASE_PATH + u'system/'
            os.path.exists('upload_path')
            filename = u'system_' + str(current_time) + '.' +meta['filename'].split('.')[-1]
            filepath = os.path.join(upload_path, filename)
            with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
            data.append(settings.IMG_BASE_URL + 'system/{}'.format(filename))
        res = {"errno": 0, "data": data}
        utiltool.response_write(self, res)


class AddNewsHandler(WebBaseHandler):
    """
    上新闻
    """
    @gen.coroutine
    def post(self):
        title = self.get_argument('title', '')
        type = self.get_argument('type', '0')
        content = self.get_argument('content', '')
        is_first = self.get_argument('is_first', '0')
        current_time = timetool.get_timestamp()
        user_name = "admin"
        print content.encode('utf-8')
        res = yield newsm.add_news_2_mysql(title, content, user_name, current_time, is_first, type)
        # 系统消息需要添加推送任务
        if type == '1':
            info_id = yield newsm.get_push_info_id(current_time)
            yield newsm.add_psuh_task(2, info_id)
        result = {"code": "0", "msg": u"插入成功"} if res else {"code": "1", "msg": u"插入失败"}
        utiltool.response_write(self, result)


class NewsListHandler(WebBaseHandler):
    """
    报名信息列表
    """
    @gen.coroutine
    def get(self):
        type = self.get_argument('type', '0')
        sort = self.get_argument('sort', '')
        rows = self.get_argument('rows', '')
        page = self.get_argument('page', '')
        order = self.get_argument('order', '')
        info = yield newsm.get_news_list(type, sort, rows, page, order)
        for item in info[0]:
            item['pubtime'] = timetool.convert_timestamp_to_date(item['pubtime'])
        res = dict(
            total=info[1],
            rows=info[0]
        )
        utiltool.response_write(self, res)


class NewsDetailHandler(WebBaseHandler):
    """
    报名信息详情
    """
    @gen.coroutine
    def get(self):
        news_id = self.get_argument('news_id', '')
        info = yield newsm.get_news_detail(news_id)
        # info['pubtime'] = timetool.convert_timestamp_to_date(info['pubtime'])
        utiltool.response_write(self, {"code": "0", "info": info})


class DelNewsHandler(WebBaseHandler):
    """
    删新闻
    """
    @gen.coroutine
    def post(self):
        news_id = self.get_argument('news_id', '')
        res = yield newsm.del_news_from_mysql(news_id)
        result = {"code": "0", "msg": u"删除成功"} if res else {"code": "1", "msg": u"删除失败"}
        utiltool.response_write(self, result)


class UpdateNewsHandler(WebBaseHandler):
    """
    改新闻
    """
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        title = self.get_argument('title', '')
        content = self.get_argument('content', '')
        news_id = self.get_argument('news_id', '0')
        print content.encode('utf-8')
        res = yield newsm.update_news_2_mysql(title, content, news_id, current_time)
        result = {"code": "0", "msg": u"插入成功"} if res else {"code": "1", "msg": u"插入失败"}
        utiltool.response_write(self, result)



class NewsToCircleHandler(WebBaseHandler):
    """
    系统消息到考友圈
    """
    @gen.coroutine
    def post(self):
        is_first = self.get_argument('is_first', '0')
        news_id = self.get_argument('news_id', '0')
        yield newsm.news_to_circle(news_id, is_first)
        result = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, result)



class UeditorHandler(WebBaseHandler):
    """
    系统消息到考友圈
    """
    @gen.coroutine
    def get(self):
        utiltool.response_write(self, {})

    @gen.coroutine
    def post(self):
        utiltool.response_write(self, {})